package com.butnet.myframe.template.impl;

import com.butnet.myframe.template.Template;
import com.butnet.myframe.template.TemplateLexerListener;
import com.butnet.myframe.template.TemplateNode;
import com.butnet.myframe.template.TemplateNodeFactory;

public class TemplateNodeFacotryImpl implements TemplateNodeFactory, TemplateLexerListener {
	public static final String END = "end";
	public static final String keys[] = { "if", "for" };
	/**
	 * 结点属性的字符串名称
	 */
	public static final String ATTRIBUTE_STRING_CONTENT_NAME = "attStr";
	public static final String ATTRIBUTE_TYPE_NAME = "type";
	public static final String TYPE_TEXT = "text";
	public static final String TYPE_EXPRESSION = "expression";

	private TemplateNode root = new TemplateNodeImpl(TemplateNodeImpl.ROOT);
	private TemplateNode currentNode = null;

	@Override
	public void parse(Template template) {
		template.setRoot(root);
		currentNode = null;
	}

	@Override
	public void append(String content, ContentType type) {
		if (currentNode == null) {
			currentNode = root;
			root.setAttribute(ATTRIBUTE_TYPE_NAME, TYPE_EXPRESSION);
			root.setAttribute(ATTRIBUTE_STRING_CONTENT_NAME, "Root");
		}
		if (type == ContentType.TEXT) {
			TemplateNode n = new TemplateNodeImpl(TemplateNodeImpl.TEXT);
			n.setTextContent(content);
			n.setAttribute(ATTRIBUTE_TYPE_NAME, TYPE_TEXT);
			currentNode.appendChild(n);
		} else if (type == ContentType.EXPRESSION) {
			content = content.trim();
			if (content.equalsIgnoreCase(END)) {
				TemplateNode n = currentNode;
				boolean break_while = false;
				while (n != null) {
					for (String key : keys) {
						if (key.equalsIgnoreCase(n.getNodeName())) {
							currentNode = n.getParentNode() != null ? n.getParentNode() : root;
							break_while = true;
						}
					}
					if (break_while)
						break;
					else
						n = n.getParentNode();
				}
			} else {
				String[] s = content.split("\\s|[^\\w]");
				String name = s.length > 0 ? s[0] : "";
				TemplateNode newNode = new TemplateNodeImpl(TemplateNodeImpl.EXPRESSION, name);
				newNode.setAttribute(ATTRIBUTE_TYPE_NAME, TYPE_EXPRESSION);
				if (s.length > 1){
					newNode.setAttribute(ATTRIBUTE_STRING_CONTENT_NAME, content.substring(name.length()));
					newNode.setTextContent(content.substring(name.length()));
				}
				currentNode.appendChild(newNode);
				currentNode = newNode;
			}
		}
	}
}
